//
//  CZRefreshControl.swift
//  git
//
//  Created by 徐 鹏超 on 16/4/13.
//  Copyright © 2016年 徐 鹏飞. All rights reserved.
//

import UIKit

enum CZRefreshStatus: Int{
    
    case Normal = 0
    case Pulling = 1
    case Loading = 2
}

class CZRefreshControl: UIControl {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var oldStatus: CZRefreshStatus = .Normal
    var status: CZRefreshStatus = .Normal{
        didSet{
            switch status{
                
              case .Normal : messageLabel.text = "下拉刷新"
              if oldStatus == .Loading{
                var inset = scrollView?.contentInset
                inset?.top = (inset?.top)! - self.frame.size.height
                scrollView?.contentInset = inset!
                oldStatus = .Normal
                }
              
              case .Pulling: messageLabel.text = "释放更新"
                
              case .Loading : messageLabel.text = "加载中"
              var inset = scrollView?.contentInset
              inset?.top = (inset?.top)! + self.frame.size.height
              scrollView?.contentInset = inset!
              oldStatus = .Loading
                
                
                sendActionsForControlEvents(UIControlEvents.ValueChanged)
              
//              endRefreshing()

            }
            
            
        }
    }
    
    func endRefreshing(){
        status = .Normal
    }

    
    private func setupUI(){
        
        // 设置frame
        var frame = self.frame
        
        frame.size.width = kUIScreenWidth
        frame.size.height = 50
        frame.origin.y = -50
        self.frame = frame
        
        
        backgroundColor = UIColor.yellowColor()
        
        addSubview(iconImageView)
        addSubview(messageLabel)
        
        
        // 约束
        iconImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(iconImageView.snp_right).offset(0)
            make.centerY.equalTo(self.snp_centerY)
            
        }
    }
    
    var scrollView: UIScrollView?

    //MARK:-- 当创建好UIControl好之后,会把他添加到 tableView
    // 这个方法 会在 将 control添加到 tableView上的时候调用
    // newSuperview 要添加到的view -> UITableView
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        // UIScroolView 的子类: UITableView,UICollectionView
        // 最好先判断一下 newSuperview 是不是 UITabelView
        if newSuperview is UIScrollView{
            printLog("添加到tableView")
            scrollView = newSuperview as? UIScrollView
            
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        }
    }
    
    //MARK:-- 监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        //  object: AnyObject? 是观察的对象
        //  我们可以把 object 转换成 观察对象的类型
        //         scrollView = object as? UIScrollView
        //        printLog(scrollView?.contentOffset.y)
        // 为什么是 负值
        // 为什么会报这个错误? scrollView是可选项,在这里我们强制解包
        
        if scrollView!.dragging {
            
            //            printLog("拖拽")
            // 由下拉刷新 -> 释放更新
            // 有释放更新 -> 下拉刷新
            if scrollView?.contentOffset.y < -120 && status == .Normal{
                printLog("释放更新")
                status = .Pulling
            } else if scrollView?.contentOffset.y > -120 && status == .Pulling{
                printLog("下拉刷新")
                status = .Normal
            }
            
        } else {
            //            printLog("放手")
            
            if scrollView?.contentOffset.y < -120 && status == .Pulling{
                printLog("去加载数据了")
                status = .Loading
            }
            
        }
    }

    
    
    //MARK:--懒加载
    
    /// 下拉刷新的图片
    private lazy var iconImageView: UIImageView = {
        
        let img = UIImageView()
        
        img.image = UIImage(named: "tableview_pull_refresh")
        
        return img
    }()
    /// 提示
    private lazy var messageLabel: UILabel = {
        
        let label = UILabel()
        
        label.text = "下拉刷新"
        
        return label
    }()


}
